package xhwl.retrofitrx;

import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;

import com.trello.rxlifecycle.components.RxActivity;
import com.trello.rxlifecycle.components.support.RxFragment;
import com.trello.rxlifecycle.components.support.RxFragmentActivity;

import rx.Subscriber;

/**
 * Created by admin on 2017/1/12.
 */

public class ProgressSubscriber<T> extends Subscriber<T> {
    private static int CONTEXT_TYPE_RXACTIVITY=0;
    private static int CONTEXT_TYPE_RXFRGACTIVITY=1;
    private static int CONTEXT_TYPE_RXFRG=2;
    /*是否弹框*/
    private boolean showPorgress = true;
    //    回调接口
    private OnNextListener onNextListener;
    //    软引用反正内存泄露
    private RxActivity rxActivity;
    private RxFragmentActivity rxFgtActivity;
    private RxFragment rxFgt;
    //    加载框可自己定义
    private LoadingDialogV3 loadDialog;
    BaseApi api;
    int contextType=CONTEXT_TYPE_RXACTIVITY;
    /**
     * 构造
     */
    public ProgressSubscriber(RxActivity activity, BaseApi api, OnNextListener onNextListener) {
        contextType=CONTEXT_TYPE_RXACTIVITY;
        this.api = api;
        this.onNextListener =  onNextListener;
        this.rxActivity = activity;
        setShowPorgress(api.isShowDialog());
        if (api.isShowDialog()) {
            initProgressDialog(api.isCancle());
        }
    }
    /**
     * 构造
     */
    public ProgressSubscriber(RxFragmentActivity activity, BaseApi api, OnNextListener onNextListener) {
        contextType=CONTEXT_TYPE_RXFRGACTIVITY;
        this.api = api;
        this.onNextListener =  onNextListener;
        this.rxFgtActivity =  activity;
        setShowPorgress(api.isShowDialog());
        if (api.isShowDialog()) {
            initProgressDialog(api.isCancle());
        }
    }
    /**
     * 构造
     */
    public ProgressSubscriber(RxFragment frg, BaseApi api, OnNextListener onNextListener) {
        contextType=CONTEXT_TYPE_RXFRG;
        this.api = api;
        this.onNextListener =  onNextListener;
        this.rxFgt =  frg;
        setShowPorgress(api.isShowDialog());
        if (api.isShowDialog()) {
            initProgressDialog(api.isCancle());
        }
    }

    /**
     * 初始化加载框
     */
    private void initProgressDialog(boolean cancel) {
        Context context=getContext();
        if (loadDialog == null && context != null) {
            loadDialog = new LoadingDialogV3(context);
            loadDialog.setCancelable(cancel);
            if (cancel) {
                loadDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        onCancelProgress();
                    }
                });
            }
        }
    }

    /**
     * 显示加载框
     */
    private void showProgressDialog() {
        if (!isShowPorgress()) return;
        Context context=getContext();
        if (loadDialog == null || context == null) return;
        if (!loadDialog.isShowing()) {
            loadDialog.show();
        }
    }


    /**
     * 隐藏
     */
    private void dismissProgressDialog() {
        if (!isShowPorgress()) return;
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }


    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        showProgressDialog();
        if (onNextListener != null) {
            onNextListener.onStart();
        }
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        /*需要緩存并且本地有缓存才返回*/
        {
            errorDo(e);
        }
        dismissProgressDialog();
    }


    /**
     * 错误统一处理
     *
     * @param e
     */
    private void errorDo(Throwable e) {
        Context context=getContext();
        if (context == null) return;
        if (onNextListener== null) return;
        if (e instanceof HttpException) {
            if(api.isShowErrorMsg()){
                if(HttpCode.CODE_HTTP_CONNECTION_TIMEOUT==((HttpException) e).getCode()){
                    Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
                }
                else if(HttpCode.CODE_SOCKET_CONNECTION_TIMEOUT==((HttpException) e).getCode()){
                    Toast.makeText(context, "请求超时", Toast.LENGTH_SHORT).show();
                }
            }
            onNextListener.onError((HttpException) e);
            e.printStackTrace();
        }
        /*可以在这里统一处理错误处理-可自由扩展*/
//        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }


    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {
        if (onNextListener != null) {
            onNextListener.onNext(t);
        }
    }


    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }


    public boolean isShowPorgress() {
        return showPorgress;
    }

    /**
     * 是否需要弹框设置
     *
     * @param showPorgress
     */
    public void setShowPorgress(boolean showPorgress) {
        this.showPorgress = showPorgress;
    }

    private Context getContext(){
        Context context=null;
        if(contextType==CONTEXT_TYPE_RXACTIVITY){
            context=rxActivity;
        }else if(contextType==CONTEXT_TYPE_RXFRGACTIVITY){
            context=rxFgtActivity;
        }else if(contextType==CONTEXT_TYPE_RXFRG){
            context=rxFgt.getContext();
        }
        return context;
    }
}
